package cn.ywyself.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * java请求过滤器, 打印http请求信息
 */
public class LogFilter extends OncePerRequestFilter {

    private final Logger logger = LoggerFactory.getLogger(LogFilter.class);

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        logger.debug("Starting {} {}", request.getMethod(), request.getRequestURL());

        long startTime = System.currentTimeMillis();
        filterChain.doFilter(request, response);

        logger.debug("Ending {} {}\tstatus: [{}], usage: [{}]ms\n", request.getMethod(), request.getRequestURL(), response.getStatus(), (System.currentTimeMillis() - startTime));
    }
}
